<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>WebSocket chatroom</title>
</head>
<body>
<h1>WebSocket chatroom</h1>
<br/>
<div style="background-color: #eeeeee;width: 600px;height: 300px;margin: 0 auto;border: 1px solid #ccc;">
    <div style="margin: 10px">
        <label>用户名：</label>
        <input id="username" style="width: 50%;"/>
        <button id="connect">连接</button>
    </div>
    <hr>
    <div>
        <label>聊天室</label>
        <div id="message"
             style="height: 200px;width: 99%; overflow-y: scroll;word-break: break-word;border: 1px solid #ccc;"></div>
    </div>
    <div>
        <label>消息内容：</label>
        <input id="content" style="width: 100%; height: 50px;"/>
        <div style="float: right;text-align: right">
            <button id="send" disabled>发送</button>
        </div>
    </div>
</div>
<script src="./assets/jquery-2.1.0.min.js"></script>
<script type="application/javascript">
    $(function () {
        var $username = $('#username');
        var $send = $('#send');
        var $connect = $('#connect');
        var $message = $('#message');
        var $content = $('#content');
        var connected = false;

        // 连接点击按钮
        $connect.click(function () {
            // 发送给服务端输入的用户名
            $.post('/username', {userName: $username.val()}, function () {
                if (connected) {
                    disconnect();
                } else {
                    if ($username.val())
                        connect();
                }
            });
        });

        // 消息发送
        $send.click(function () {
            if ($content.val())
                send();
        });

        // websocket连接
        function connect() {
            ws = new WebSocket('ws://localhost:8081/chatroom');
            // 连接建立事件
            ws.onopen = function (data) {
                console.log(data);
            };
            // 连接关闭事件
            ws.onclose = function (data) {
                console.log(data);
            };
            ws.onmessage = function (data) {
                // 展示收到的消息
                showMessage(data.data);
            };
            setConnected(true);
        }

        function disconnect() {
            if (ws != null) {
                ws.close();
            }
            setConnected(false);
        }

        function send() {
            ws.send($content.val());
        }

        function setConnected(b) {
            connected = b;
            if (b) {
                $send.removeAttr('disabled');
                $connect.text('退出');
            } else {
                $send.attr('disabled', true);
                $connect.text('连接');
            }
        }

        function showMessage(message) {
            $message.append("<br>" + message);
        }
    });
</script>
</body>
</html>